package com.game.logic.roles;

import akka.actor.ActorRef;
import com.coment.cfg.luban.constant.AIDCFG;
import com.coment.po.roles.Roles;
import com.game.framework.ActorManager;
import com.coment.message.roles.RolesUpdatePush;
import com.game.logic.fighting.actor.RolesActor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Component
@Aspect
public class RolesDaoLoggingAspect {
    private static final Logger logger = LoggerFactory.getLogger(RolesDaoLoggingAspect.class);
    private static final ConcurrentHashMap<String, Double> lastHp = new ConcurrentHashMap<>();

    @Around("execution(* com.game.dao.user.roles.RolesDao.save(..))")
    public Object bloodVolumeChangeMonitoring(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Roles arg = (Roles) args[0];

        String argId = arg.getId();

        if (argId != null) {
            Double argHp = arg.rolePanel.getAttribute().get(AIDCFG.hp);

            // 正确使用 computeIfPresent 并获取旧值（如果存在）
            Double previousHp = lastHp.get(argId);
            if (previousHp != null && !previousHp.equals(argHp)) {
                StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();

                if (argHp > previousHp) {
                    logger.error("{} - 血量增加: {} -> {}  定位{}", argId, previousHp, argHp, stackTrace[12].toString());
                } else {
                    logger.info("{} - 血量变更: {} -> {}  定位{}", argId, previousHp, argHp, stackTrace[12].toString());
                }
            }

            // 更新当前血量
            lastHp.put(argId, argHp);
        }

        ActorManager.getActor(RolesActor.class, argId).tell(
                new RolesUpdatePush(),
                ActorRef.noSender()
        );


        try {
            return joinPoint.proceed();
        } catch (Exception e) {
            logger.error("Error occurred while saving role", e);
            throw e;
        }
    }
}